package domo1;

import java.util.*;

public class hash {
    //找出前k个频率最高的单词
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String,Integer> map = new HashMap<>();
        for(String str : words){
            if(map.get(str) == null){
                map.put(str,1);
            } else {
                int val = map.get(str);
                map.put(str,val+1);
            }
        }
        PriorityQueue<Map.Entry<String, Integer>> minheap = new PriorityQueue<>(new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                if(o1.getValue().compareTo(o2.getValue()) == 0){
                    return o2.getKey().compareTo(o1.getKey());
                }
                return o1.getValue().compareTo(o2.getValue());
            }
        });
        for(Map.Entry<String, Integer> entry : map.entrySet()){
            if(minheap.size() < k){
                minheap.offer(entry);
            } else {
                Map.Entry<String, Integer> top = minheap.peek();
                if(top.getValue().compareTo(entry.getValue()) < 0){
                    minheap.poll();
                    minheap.offer(entry);
                } else {
                    if(top.getValue().compareTo(entry.getValue()) == 0){
                        if(top.getKey().compareTo(entry.getKey()) > 0){
                            minheap.poll();
                            minheap.offer(entry);
                        }
                    }
                }
            }
        }
        List<String> ret = new ArrayList<>();
        for(int i = 0; i < k; i++){
            Map.Entry<String, Integer> top = minheap.poll();
            ret.add(top.getKey());
        }
        Collections.reverse(ret);
        return ret;
    }

    public static void main(String[] args) {
        int a = 3;
        HashSet<Integer> set = new HashSet<>();
        System.out.println(set.add(a));
        System.out.println(set.add(a));
    }
}
